<?php
/**
 * Created by PhpStorm.
 * User: UEWARE
 * Date: 2019-7-19
 * Time: 09:35:06
 */

namespace App\Factory;

use App\Exceptions\Error;
use Overtrue\EasySms\EasySms;

class Sms
{
    /**
     * EasySms对象实例
     *
     * @var string EasySms
     */
    protected $easySms;

    /**
     * CrsSms constructor.
     *
     * @throws \Error
     */
    public function __construct()
    {
        $this->easySms = new EasySms($this->getConfig());
    }

    /**
     * 读取配置文件
     *
     * @return mixed
     * @throws \Error
     *
     * @date     2018/11/27 10:20 AM
     */
    private function getConfig()
    {
        $config = config('third_party.easy_sms');

        if (empty($config) || !is_array($config)) {
            throw new Error(100000, '短信服务配置文件错误，请检查配置文件');
        }

        return $config;
    }

    /**
     * 发送短信
     *
     * @param string $mobile   手机号
     * @param string $template 短信模板
     * @param array  $data     短信内容
     *
     * @throws Error
     */
    public function send($mobile, $template, $data)
    {
        try {
            $this->easySms->send($mobile, [
                'template' => $template,
                'data'     => $data
            ]);
        } catch (\Exception $exception) {
            $message = $exception->results['sendcloud']['exception']->raw['message'];
            throw new Error(100000, '发送短信' . $message);
        }
    }
}
